package com.billjc.activity.service;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.activiti.engine.delegate.BpmnError;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.billjc.activity.entities.Ecs;
import com.billjc.activity.util.FtpUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class UpdateImageService {
	@Value("${ftp.downloadPath}")
	private String downloadDir;
	@Value("${ftp.localPath}")
	private String localPath;
    /**
     * ftp 下载
     * @param ecs
     */
	private boolean downloadFile(Ecs ecs) {
		String remotePath = "";
		String fileName = ecs.getEFormInfo().getEFormReturn().getFormDataID();
		if (StringUtils.isNotEmpty(fileName)) {
			remotePath = downloadDir + fileName + ".tiff";
			try {
				FtpUtil.downLoadFile(remotePath, localPath);
				return true;
			} catch (Exception e) {
				log.error("从eform ftp服务器下载文件: " + fileName + "出现异常");
				e.printStackTrace();
			}
		} else {
			log.debug("没有要下载的文件");
		}
		return false;
	}
	/**
	 * 上传到影像 ftp
	 * @param ecs
	 */
	public void uploadFile(Ecs ecs) {
		downloadFile(ecs);
		String fileName = ecs.getEFormInfo().getEFormReturn().getFormDataID();
		String fileLocalPath = localPath+"\\"+fileName+".tiff";
		File localFile = new File(fileLocalPath);
		//文件是否下载成功
		if(!localFile.exists()) {
			throw new BpmnError("createError2");
		}
		try {
			FtpUtil.uploadFile(fileLocalPath);
		} catch (IOException e) {
			log.error("文件: "+fileName+",上传影像失败");
			throw new BpmnError("createError2");
		}
	}
}
